package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import com.itheima.utils.MenuUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    //获得当前登录用户的用户名和该用户所能操作的菜单
    @Reference
    private UserService userService;
    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getLoginUsername")
    public Result getLoginUsername(){
        try{
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String password = user.getPassword();
            Map<String, Object> map = new HashMap<>();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            map.put("username",username);
            //获取该用户所拥有的菜单集合，并使用递归的方式为每一个一级菜单赋值
            map.put("menu", MenuUtil.getMenuList(userService.findAllMenuByUsername(username)));
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,map);
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
